package com.ldk.api.handler;

import com.ldk.api.ApiVersion;
import com.ldk.api.CheckToken;
import com.ldk.api.Consts;
import com.ldk.api.ErrorCode;
import com.ldk.api.FileItem;
import com.ldk.api.RequestPlatform;
import com.ldk.api.ResponseObject;
import com.ldk.api.ResponseResult;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.BeanUtil;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.base.framework.util.baidu.RouteMatrixApi;
import com.ldk.base.framework.util.baidu.routematrix.RouteMatrixRequestParms;
import com.ldk.base.framework.util.baidu.routematrix.RouteMatrixResponseParmsResult;
import com.ldk.framework.entity.CommentTouser;
import com.ldk.framework.entity.Complaint;
import com.ldk.framework.entity.ComplaintImages;
import com.ldk.framework.entity.Dictdata;
import com.ldk.framework.entity.Driver;
import com.ldk.framework.entity.DriverReceiveTrip;
import com.ldk.framework.entity.LinkDriver;
import com.ldk.framework.entity.LinkUser;
import com.ldk.framework.entity.RoadLine;
import com.ldk.framework.entity.ServicePriceRecord;
import com.ldk.framework.entity.ServiceTrip;
import com.ldk.framework.entity.ServiceTripCrews;
import com.ldk.framework.entity.User;
import com.ldk.framework.enums.BillingMode;
import com.ldk.framework.enums.PayType;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.ServiceCode;
import com.ldk.framework.enums.TradePayStatus;
import com.ldk.framework.enums.TripNoType;
import com.ldk.framework.enums.TripStatus;
import com.ldk.framework.service.IAreaService;
import com.ldk.framework.service.ICommentTouserService;
import com.ldk.framework.service.IComplaintService;
import com.ldk.framework.service.IDriverReceiveTripService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IRoadLineService;
import com.ldk.framework.service.IServiceConfigAreaService;
import com.ldk.framework.service.IServiceConfigService;
import com.ldk.framework.service.IServicePriceRecordService;
import com.ldk.framework.service.IServiceTripCrewsService;
import com.ldk.framework.service.IServiceTripService;
import com.ldk.framework.service.ITenpayService;
import com.ldk.framework.service.IUserService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 司机行程模块
 *
 * @author xiangwlpushToUser
 * 2017年2月27日
 * com.ldk.api.handler
 * TripRequestHandler
 */
public class TripRequestHandler extends BZBaseRequestHandler {

    @Autowired
    private IDriverService driverService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoadLineService roadLineService;
    @Autowired
    private IServiceTripService serviceTripService;
    @Autowired
    private IServicePriceRecordService servicePriceRecordService;
    @Autowired
    private ICommentTouserService commentTouserService;
    @Autowired
    private IServiceTripCrewsService serviceTripCrewsService;
    @Autowired
    private IComplaintService complaintService;
    @Autowired
    private ITenpayService tenpayService;
    @Autowired
    private IDriverReceiveTripService driverReceiveTripService;
    @Autowired
    private IServiceConfigService serviceConfigService;
    @Autowired
    protected IAreaService areaService;
    @Autowired
    protected IServiceConfigAreaService serviceConfigAreaService;


    /**
     * 获取车等级
     *
     * @param parms
     * @return
     * @paramopenId openId
     */
    @ApiVersion(value = {1})
    public ResponseObject getCarRanks(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "getCarRanks");
        //参数检验
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        List<Dictdata> result = getDictdataList(2);//2为车等级的数据字典ID
        if (result == null || result.isEmpty()) {
            ResponseResult.exception(response, ErrorCode.TRIP_CAR_RANK_EMPTY);
        } else {
            ResponseResult.success(response, result);
        }

        return response;
    }

    /**
     * 估算两点间的费用
     *
     * @param parms
     * @return
     * @paramserviceCode 服务业务代码
     * @paramroadId 路线ID
     * @paramcarType 车型
     * @paramstartLon 出发地点经度
     * @paramstartLat 出发地点纬度
     * @paramendLon 目的地点经度
     * @paramendLat 目的地点纬度
     * @paramcrewCount 乘客人数，默认0
     */
    @ApiVersion(value = {1})
    public ResponseObject estimateFee(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "estimateFee");
        //参数检验
        if (!checkRequireParms(parms, "serviceCode", "carType", "roadId", "startLon", "startLat", "endLon", "endLat")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        Double startLon = ConvertUtil.parseDouble(parms.get("startLon"));
        Double startLat = ConvertUtil.parseDouble(parms.get("startLat"));
        Double endLon = ConvertUtil.parseDouble(parms.get("endLon"));
        Double endLat = ConvertUtil.parseDouble(parms.get("endLat"));
        Long roadId = ConvertUtil.parseLong(parms.get("roadId"));
        String carType = ConvertUtil.parseString(parms.get("carType"));
        Integer crewCount = ConvertUtil.parseInt(parms.get("crewCount"));

        //出发地点为空
        if (startLon == null || startLon == 0 ||
                startLat == null || startLat == 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_START_EMPTY);
        }
        //目的地点为空
        if (endLon == null || endLon == 0 ||
                endLat == null || endLat == 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_END_EMPTY);
        }
        if (StringUtils.isBlank(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_EMPTY);
        }
        /**
         * mqy 20200904
         *  订单所在地区,预先默认
         * */
        String areaCode = Consts.AREA_CODE;
        Map<String, Object> result = serviceTripService.estimateFee("", serviceCode, carType, roadId, startLon, startLat, endLon, endLat, crewCount, Consts.BAIDU_MAP_AK, areaCode);
        Boolean success = result.containsKey("success") ? ConvertUtil.parseBoolean(result.get("success")) : false;
        if (success) {
            Double fee = result.containsKey("fee") ? ConvertUtil.parseDouble(result.get("fee")) : 0;
            ResponseResult.success(response, fee);
            //ResponseResult.success(response, result);
        } else {
            ResponseResult.exception(response, ErrorCode.TRIP_ESTIMATE_FAILED);
        }
        return response;
    }

    /**
     * 估算两点间的费用
     *
     * @param parms
     * @return
     * @paramserviceCode 服务业务代码
     * @paramroadId 路线ID
     * @paramcarType 车型
     * @paramstartLon 出发地点经度
     * @paramstartLat 出发地点纬度
     * @paramendLon 目的地点经度
     * @paramendLat 目的地点纬度
     * @paramcrewCount 乘客人数，默认0
     */
    @ApiVersion(value = {1})
    public ResponseObject estimateFeeV2(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "estimateFeeV2");
        //参数检验
        if (!checkRequireParms(parms, "serviceCode", "carType", "roadId", "startLon", "startLat", "endLon", "endLat")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        Double startLon = ConvertUtil.parseDouble(parms.get("startLon"));
        Double startLat = ConvertUtil.parseDouble(parms.get("startLat"));
        Double endLon = ConvertUtil.parseDouble(parms.get("endLon"));
        Double endLat = ConvertUtil.parseDouble(parms.get("endLat"));
        Long roadId = ConvertUtil.parseLong(parms.get("roadId"));
        String carType = ConvertUtil.parseString(parms.get("carType"));
        Integer crewCount = ConvertUtil.parseInt(parms.get("crewCount"));


        //出发地点为空
        if (startLon == null || startLon == 0 ||
                startLat == null || startLat == 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_START_EMPTY);
        }
        //目的地点为空
        if (endLon == null || endLon == 0 ||
                endLat == null || endLat == 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_END_EMPTY);
        }
        if (StringUtils.isBlank(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_EMPTY);
        }
        /**
         * mqy 20200904
         *  订单所在地区,预先默认
         * */
        String areaCode = Consts.AREA_CODE;
        Map<String, Object> result = serviceTripService.estimateFee("", serviceCode, carType, roadId, startLon, startLat, endLon, endLat, crewCount, Consts.BAIDU_MAP_AK, areaCode);
        Boolean success = result.containsKey("success") ? ConvertUtil.parseBoolean(result.get("success")) : false;
        if (success) {
            // Double fee = result.containsKey("fee") ? ConvertUtil.parseDouble(result.get("fee")) : 0;
            ResponseResult.success(response, result);
        } else {
            ResponseResult.exception(response, ErrorCode.TRIP_ESTIMATE_FAILED);
        }
        return response;
    }

    /**
     * 获取路线
     *
     * @param parms
     * @return
     * @paramopenId
     * @paramserviceCode
     */
    @ApiVersion(value = {1})
    public ResponseObject getRoadLines(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("zxpc", "getRoadLines");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));

        if (StringUtils.isBlank(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_EMPTY);
        }
        RoadLine query = new RoadLine();
        query.setServiceCode(serviceCode);
        query.setEnabled(true);

        List<RoadLine> result = roadLineService.selectList("", query);
        if (result == null || result.isEmpty()) {
            response = ResponseResult.exception(response, ErrorCode.TRIP_ROAD_LINE_EMPTY);
        } else {
            response = ResponseResult.success(response, result);
        }

        return response;
    }

    /**
     * 司机发布行程
     *
     * @param parms
     * @return
     * @paramopenId司机openId
     * @paramserviceCode 服务业务代码
     * @paramstartLocation 出发地点
     * @paramstartLon 出发地点经度
     * @paramstartLat 出发地点纬度
     * @paramendLocation 目的地点
     * @paramendLon 目的地点经度
     * @paramendLat 目的地点纬度
     * @paramgoTime 出发时间 时间格式yyyy-MM-dd HH:mm:ss
     * @paramcrewCount 默认已有乘客数
     * @paramroadId 行程路线，专线拼车业务时必须填，其它可以为空
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverPublish(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "publish");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode", "startLocation", "startLon", "startLat",
                "endLocation", "endLon", "endLat", "goTime", "crewCount")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        String startLocation = ConvertUtil.parseString(parms.get("startLocation"));
        Double startLon = ConvertUtil.parseDouble(parms.get("startLon"));
        Double startLat = ConvertUtil.parseDouble(parms.get("startLat"));
        String endLocation = ConvertUtil.parseString(parms.get("endLocation"));
        Double endLon = ConvertUtil.parseDouble(parms.get("endLon"));
        Double endLat = ConvertUtil.parseDouble(parms.get("endLat"));
        String goTime = ConvertUtil.parseString(parms.get("goTime"));
        Integer crewCount = ConvertUtil.parseInt(parms.get("crewCount"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        if (StringUtils.isBlank(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_EMPTY);
        }
        //出发地点为空
        if (StringUtils.isBlank(startLocation) ||
                startLon == null || startLon == 0 ||
                startLat == null || startLat == 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_START_EMPTY);
        }
        //目的地点为空
        if (StringUtils.isBlank(endLocation) ||
                endLon == null || endLon == 0 ||
                endLat == null || endLat == 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_END_EMPTY);
        }
        //出发时间为空
        if (StringUtils.isBlank(goTime)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_GO_TIME_EMPTY);
        }
        //判断司机是否已经存在发布该服务业务的行程
        //这几种状态是不能再发布相同服务业务的行程
        int status = TripStatus.Publish.getValue()
                | TripStatus.Accept.getValue()
                | TripStatus.Go.getValue()
                | TripStatus.WaitingPerson.getValue()
                | TripStatus.OnTheCar.getValue()
                | TripStatus.OFFTheCar.getValue();
        ServiceTrip tripQuery = new ServiceTrip();
        tripQuery.setOpenId(openId);
        tripQuery.setStatus(status);
        tripQuery.setServiceCode(serviceCode);
        long count = serviceTripService.selectCount("", tripQuery);
        //存在相同的未结束的行程(取消和完成状态)为行程结束状态
        if (count > 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_SAME_SERVICE_EXIST);
        }
        //两点间路线距离估算
        RouteMatrixRequestParms request = new RouteMatrixRequestParms.Builder()
                .setOrigins(String.format("%s,%s", startLat, startLon))
                .setDestinations(String.format("%s,%s", endLat, endLon))
                .setOutput("json")
                .setTactics("11")
                .setAk(Consts.BAIDU_MAP_AK)
                .build();
        RouteMatrixResponseParmsResult routeMatrixResult = RouteMatrixApi.driving(request);
        //无法估计距离
        if (routeMatrixResult == null || routeMatrixResult.getDistance().getValue() == null) {
            return ResponseResult.exception(response, ErrorCode.ROUTE_MATRIX_FAILED);
        }
        ServiceTrip entity = new ServiceTrip();
        Boolean success = false;
        try {
            double distance = routeMatrixResult.getDistance().getValue();
            double duration = routeMatrixResult.getDuration().getValue();

            Long lGoTime = SystemUtil.stringToSeconds(goTime, "yyyy-MM-dd HH:mm:ss");
            entity.setTripNo(SystemUtil.generateOrderNo(TripNoType.TRIP.getPrefix()));
            entity.setOpenId(openId);
            entity.setServiceCode(serviceCode);
            entity.setUserType(PlatformUserType.DRIVER_USER.getValue());
            entity.setRoadId(0l);
            entity.setStartLocation(startLocation);
            entity.setStartLon(startLon);
            entity.setStartLat(startLat);
            entity.setEndLocation(endLocation);
            entity.setEndLon(endLon);
            entity.setEndLat(endLat);
            entity.setCreateTime(SystemUtil.getAllSeconds());
            entity.setGoTime(lGoTime);
            entity.setStatus(TripStatus.Publish.getValue());
            entity.setCrewCount(crewCount);
            entity.setCarSeats(driver.getCarSeats());
            entity.setCarRank(driver.getCarRank());
            entity.setHasAsign(false);
            entity.setHasComment(false);
            //单位米
            entity.setDistance(distance);
            //单位秒
            entity.setDuration(duration);

            //单位米
            entity.setDistance(distance);
            //单位秒
            entity.setDuration(duration);
            entity.setHasAsign(false);
            entity.setHasComment(false);
            entity.setTripType(1);
            entity.setBillingMode(BillingMode.Distance.getValue());
            //double tmpPayFee = ConvertUtil.toRoundFiexd(totalFee);
            //entity.setPayFee(tmpPayFee);
            entity.setCompanyId(driver.getCompanyId());
            entity.setAreaCode(driver.getAreaCode());
            //司机发布行程
            success = serviceTripService.driverPublishTrip("", entity);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            response = ResponseResult.success(response, entity);
        } else {
            response = ResponseResult.exception(response, ErrorCode.TRIP_PUBLISH_FAILED);
        }
        return response;
    }

    /**
     * 司机取消自己发布的行程
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramserviceCode 服务业务代码
     * @paramdriverTripNo 司机的行程单号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverCancelTrip(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverCancelTrip");
        //参数检验
        if (!checkRequireParms(parms, "openId", "driverTripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //业务代码为空表示所有业务
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        //判断是不是司机的行程
        ServiceTrip query = new ServiceTrip();
        query.setOpenId(openId);
        query.setTripNo(driverTripNo);
        ServiceTrip driverTrip = serviceTripService.selectOne("", query);
        if (driverTrip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }

        //判断状态
        //只有这些状态才能取消
        int canCancelTripStatus = TripStatus.Publish.getValue()
                + TripStatus.Accept.getValue() + TripStatus.Go.getValue() + TripStatus.WaitingPerson.getValue();
        int driverTripStatus = driverTrip.getStatus();
        if ((driverTripStatus & canCancelTripStatus) != driverTripStatus) {
            return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
        }
        Boolean success = false;
        try {
            success = serviceTripService.driverCancelTrip("", driverTrip);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "取消行程成功");
        } else {
            ResponseResult.exception(response, ErrorCode.TRIP_DRIVER_CANCEL_TRIP_FAILED);
        }


        return response;
    }


    /**
     * 司机取消用户行程
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramserviceCode 服务业务代码
     * @paramdriverTripNo 司机的行程单号
     * @paramuserTripNo 用户的行程单号
     * @paramreason 取消原因
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverCancelUserTrip(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverCancelUserTrip");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode", "driverTripNo", "userTripNo", "reason")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //业务代码为空表示所有业务
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        String userTripNo = ConvertUtil.parseString(parms.get("userTripNo"));
        String reason = ConvertUtil.parseString(parms.get("reason"));
        //判断是不是司机的行程
        ServiceTrip query = new ServiceTrip();
        query.setServiceCode(serviceCode);
        query.setOpenId(openId);
        query.setTripNo(driverTripNo);
        ServiceTrip driverTrip = serviceTripService.selectOne("", query);
        if (driverTrip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //设置原因，底层使用
        driverTrip.setRemark(reason);

        //判断用户行程是否存在且是改司机接单的
        query = new ServiceTrip();
        query.setServiceCode(serviceCode);
        query.setTripNo(userTripNo);
        query.setDriverOpenId(openId);
        ServiceTrip userTrip = serviceTripService.selectOne("", query);
        if (userTrip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //设置原因，底层使用
        userTrip.setRemark(reason);

        //判断用户是不是司机行程的乘客行程
        ServiceTripCrews tripCrewQuery = new ServiceTripCrews();
        tripCrewQuery.setDriverTripNo(driverTripNo);
        tripCrewQuery.setCrewTripNo(userTripNo);
        tripCrewQuery.setDriverOpenId(openId);
        ServiceTripCrews tripCrew = serviceTripCrewsService.selectOne("", tripCrewQuery);
        if (tripCrew == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_CREW_NOT_EXIST);
        }
        //判断状态
        //只有这些状态才能取消
        int canCancelTripStatus = TripStatus.Accept.getValue()
                + TripStatus.Payed.getValue() + TripStatus.WaitingPerson.getValue();
        //包车是先发车后上车
        if (ServiceCode.BC.getCode().equals(serviceCode)) {
            canCancelTripStatus += TripStatus.Go.getValue();
        } else {
            canCancelTripStatus += TripStatus.OnTheCar.getValue();
        }
        int driverTripStatus = driverTrip.getStatus();
        if ((driverTripStatus & canCancelTripStatus) != driverTripStatus) {
            return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
        }
        //只有这些状态才能取消
        int userTripStatus = userTrip.getStatus();
        if (!((userTripStatus & canCancelTripStatus) == driverTripStatus)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
        }
        Boolean success = false;
        try {
            success = serviceTripService.driverCancelUserTrip("", driverTrip, userTrip, tripCrew);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "取消行程成功");
        } else {
            ResponseResult.exception(response, ErrorCode.TRIP_DRIVER_CANCEL_TRIP_FAILED);
        }
        return response;
    }

    /**
     * 司机获取用户新行程列表
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramserviceCode 服务业务代码
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverGetUserNewTripList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverGetUserNewTripList");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //业务代码为空表示所有业务
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;
        Sort sort = new Sort(Direction.DESC, "create_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);
        ServiceTrip query = new ServiceTrip();
        query.setServiceCode(serviceCode);
        query.setUserType(PlatformUserType.CLIENT_USER.getValue());
        query.setStatus(TripStatus.Publish.getValue());
        //query.setDriverOpenId(openId);

        List<ServiceTrip> result = serviceTripService.selectList("", query, pageable);

        response = ResponseResult.success(response, result);

        return response;
    }

    /**
     * 司机能接受用户行程列表
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramserviceCode 服务业务代码
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverCanAcceptUserTripList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverCanAcceptUserTripList");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }

        //获取司机在行程中的订单
        int status2 = //TripStatus.Publish.getValue()|
                TripStatus.Accept.getValue()
                        | TripStatus.Go.getValue()
                        | TripStatus.WaitingPerson.getValue()
                        | TripStatus.OnTheCar.getValue()
                        | TripStatus.OFFTheCar.getValue();
        ServiceTrip driverquery = new ServiceTrip();
        driverquery.setUserType(PlatformUserType.DRIVER_USER.getValue());
        driverquery.setStatus(status2);
        driverquery.setDriverOpenId(openId);
        Sort sort2 = new Sort(Direction.ASC, "go_time");
        List<ServiceTrip> result2 = serviceTripService.selectList("", driverquery, sort2);
        List<ServiceTrip> triping = new ArrayList<>();
        for (ServiceTrip trip : result2) {
            if (trip.getServiceCode().equals(ServiceCode.KC.getCode())
                    || trip.getServiceCode().equals(ServiceCode.ZC.getCode())) {
                triping.add(trip);
            }
        }
        List<ServiceTrip> result = null;
        if (triping.size() == 0) {
            //业务代码为空表示所有业务
            String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
            DriverReceiveTrip receiveTripQuery = new DriverReceiveTrip();
            receiveTripQuery.setDriverOpenId(openId);
            List<DriverReceiveTrip> receiveTripList = driverReceiveTripService.selectList("", receiveTripQuery);
            if (receiveTripList != null && receiveTripList.size() > 0) {
                List<String> tripNoList = new ArrayList<String>();
                for (DriverReceiveTrip item : receiveTripList) {
                    tripNoList.add(item.getTripNo());
                }
                //发布或定金已支付的
                int status = TripStatus.Publish.getValue();
                ServiceTrip query = new ServiceTrip();
                query.setServiceCode(serviceCode);
                query.setUserType(PlatformUserType.CLIENT_USER.getValue());
                query.setStatus(status);
                result = serviceTripService.selectListIn("", query, tripNoList);
            }
        }

        //获取城际通排班订单
        int status1 = TripStatus.Accept.getValue() | TripStatus.Go.getValue()
                | TripStatus.OnTheCar.getValue() | TripStatus.OFFTheCar.getValue();
        ServiceTrip cjtquery = new ServiceTrip();
        cjtquery.setServiceCode(ServiceCode.CJT.getCode());
        cjtquery.setUserType(PlatformUserType.DRIVER_USER.getValue());
        cjtquery.setDriverOpenId(openId);
        cjtquery.setStatus(status1);
        Sort sort = new Sort(Direction.ASC, "go_time");

        List<ServiceTrip> result1 = serviceTripService.selectList("", cjtquery, sort);
        if (triping.size() == 0) {
            if (result != null && result.size() > 0) {
                if (result1 != null && result1.size() > 0) {
                    result.addAll(result1);
                }
                response = ResponseResult.success(response, result);
            } else {
                response = ResponseResult.success(response, result1);
            }
        } else {
            triping.addAll(result1);
            response = ResponseResult.success(response, triping);
        }
        return response;
    }


    /**
     * 司机获取接受用户行程列表
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramserviceCode 服务业务代码
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverGetAcceptUserTripList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverGetAcceptUserTripList");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //业务代码为空表示所有业务
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;
        Sort sort = new Sort(Direction.DESC, "create_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);
        ServiceTrip query = new ServiceTrip();
        query.setServiceCode(serviceCode);
        query.setUserType(PlatformUserType.CLIENT_USER.getValue());
        query.setStatus(TripStatus.Accept.getValue());
        query.setDriverOpenId(openId);

        List<ServiceTrip> result = serviceTripService.selectList("", query, pageable);
        response = ResponseResult.success(response, result);

        return response;
    }

    /**
     * 司机获取自己的行程列表
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramserviceCode 服务业务代码
     * @paramstatus 行程状态 支持状态|运算值查询
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverGetSelfTripList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverGetSelfTripList");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode", "status", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //业务代码为空表示所有业务
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        int status = ConvertUtil.parseInt(parms.get("status"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;
        Sort sort = new Sort(Direction.DESC, "create_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);
        ServiceTrip query = new ServiceTrip();
        query.setServiceCode(serviceCode);
        //query.setOpenId(openId);
        query.setDriverOpenId(openId);
        query.setStatus(status);
        query.setUserType(PlatformUserType.DRIVER_USER.getValue());

        List<ServiceTrip> result = serviceTripService.selectList("", query, pageable);

        response = ResponseResult.success(response, result);
        return response;
    }

    /**
     * 司机获取自己发布的行程列表
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramserviceCode 服务业务代码
     * @paramstatus 行程状态 支持状态|运算值查询
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverMySelfTripList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverMySelfTripList");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode", "status", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //业务代码为空表示所有业务
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        int status = ConvertUtil.parseInt(parms.get("status"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;
        Sort sort = new Sort(Direction.DESC, "create_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);
        ServiceTrip query = new ServiceTrip();
        query.setServiceCode(serviceCode);
        query.setOpenId(openId);
        query.setStatus(status);
        query.setUserType(PlatformUserType.DRIVER_USER.getValue());
        List<ServiceTrip> result = serviceTripService.selectList("", query, pageable);

        response = ResponseResult.success(response, result);
        return response;
    }

    /**
     * 司机获取行程乘客订单列表
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramtripNo 司机行程单号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", check = true, platform = RequestPlatform.driver)
    public ResponseObject driverGetTripCrewsList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverGetTripCrewsList");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        ServiceTripCrews query = new ServiceTripCrews();
        query.setDriverTripNo(tripNo);
        query.setDriverOpenId(openId);
        query.setCanceled(false);
        List<ServiceTripCrews> result = serviceTripCrewsService.selectList("", query);

        response = ResponseResult.success(response, result);
        return response;
    }

    /**
     * 司机拒绝行程
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramtripNo 用户行程号
     * @paramreason 拒绝理由内容
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverRefuse(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverRefuse");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo", "reason")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        String reason = ConvertUtil.parseString(parms.get("reason"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //判断用户行程是否存在
        ServiceTrip userTripQuery = new ServiceTrip();
        userTripQuery.setTripNo(tripNo);
        ServiceTrip userTrip = serviceTripService.selectOne("", userTripQuery);
        if (userTrip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //能拒绝的行程状态值(发布或支付定金)
        /*if (userTrip.getStatus() != TripStatus.Publish.getValue()
            && userTrip.getStatus() != TripStatus.DepositPayed.getValue()) {
			return ResponseResult.exception(response,ErrorCode.TRIP_STATUS_ERROR);
		}*/
        if (userTrip.getStatus() != TripStatus.Publish.getValue()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
        }
        Boolean success = false;
        try {
            success = serviceTripService.driverRefuse("", openId, userTrip, reason);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            response = ResponseResult.success(response, "拒绝行程成功");
        } else {
            response = ResponseResult.exception(response, ErrorCode.TRIP_DRIVER_REFUSE_APPLY_FAILED);
        }
        return response;
    }


    /**
     * 用户支付行程定金
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @paramtripNo 行程编号
     * @parampayId支付方式ID 支付宝 微信 余额
     * @paramip 微信支付时 客户端终端IP,其他支付时为空
     * @parampayPwd 支付密码 余额支付时必须，其他支付时为空
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject userPayTripDeposit(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "userPayTripDeposit");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo", "payId", "ip", "payPwd")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        Integer payId = ConvertUtil.parseInt(parms.get("payId"));
        String ip = ConvertUtil.parseString(parms.get("ip"));
        String payPwd = ConvertUtil.parseString(parms.get("payPwd"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        //必须是支付宝,微信支付和余额支付
        if (payId != PayType.Alipay.getId() &&
                payId != PayType.Tenpay.getId() &&
                payId != PayType.Balance.getId()) {
            return ResponseResult.exception(response, ErrorCode.PAYMENT_NOT_EXIST);
        }
        //如果是微信支付，需要判断openId,ip不能为空
        if (payId == PayType.Tenpay.getId()) {
            if (StringUtils.isBlank(ip)) {
                return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
            }
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        //判断用户是否存在
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }

        //自己的专线拼车行程
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        query.setOpenId(openId);
        //获取行程
        ServiceTrip trip = serviceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        /*if (trip.getStatus() == TripStatus.DepositPayed.getValue()) {
			return ResponseResult.exception(response, ErrorCode.TRIP_DEPOSIT_PAYED);
		}*/
        //判断行程状态和支付状态
        if (trip.getDepositPayStatus() != null &&
                (trip.getDepositPayStatus() == TradePayStatus.TRADE_SUCCESS.getValue() ||
                        trip.getDepositPayStatus() == TradePayStatus.TRADE_FINISHED.getValue())) {
            return ResponseResult.exception(response, ErrorCode.TRIP_DEPOSIT_PAYED);
        }
        //double depositFee = 0.01;
        double depositFee = trip.getDepositPayFee();
        //支付金额小于等于0
        if (depositFee <= 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_PAYFEE_LESS_ZERO);
        }
        //如果是余额支付判断用户余额是否大于行程支付费用
        if (payId == PayType.Balance.getId()) {
            //判断支付密码
            if (StringUtils.isBlank(payPwd)) {
                return ResponseResult.exception(response, ErrorCode.USER_PAY_PWD_EMPTY);
            }
            String ecPayPwd = encodePayPwd(payPwd);
            //支付密码是否正确
            if (!ecPayPwd.equals(user.getPayPwd())) {
                return ResponseResult.exception(response, ErrorCode.USER_PAY_PWD_ERROR);
            }

            double balance = user.getBalance() == null ? 0 : user.getBalance();
            //余额不能小于0，支付费用不能大于余额，表示用户余额不足
            if (balance <= 0 || depositFee > balance) {
                return ResponseResult.exception(response, ErrorCode.USER_BALANCE_NOT_ENOUGH);
            }
        }
        Boolean success = false;
        try {
            //支付方式
            String payName = PayType.getPayName(payId);
            //
            //修改行程支付相关的
            ServiceTrip entity = new ServiceTrip();
            entity.setTripNo(tripNo);
            entity.setDepositPayId(payId);
            entity.setDepositPayName(payName);
            entity.setDepositPayStatus(TradePayStatus.WAIT_BUYER_PAY.getValue());
            int row = serviceTripService.updateByKey("", entity);
            success = row > 0;
            //余额支付直接调支付方法，不像支付宝和微信要等待回调再调用支付方法
            if (payId == PayType.Balance.getId()) {
                success = serviceTripService.payTripDeposit("", tripNo, null, null, null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        //成功返回支付相关信息
        if (success) {
            try {
                //重新获取一次
                trip = serviceTripService.selectOne("", query);
                Map<String, Object> result = null;
                if (payId == PayType.Balance.getId()) {
                    result = BeanUtil.toMapByFastjson(trip);
                } else {
                    result = setTripPayDepositCallback(trip, payId, ip);
                }
                ResponseResult.success(response, result);
            } catch (Exception e) {
                logger.error(e.getMessage());
                ResponseResult.exception(response, ErrorCode.TRIP_SET_DEPOSIT_CALLBACK_FAILED);
            }
        } else {
            ResponseResult.exception(response, ErrorCode.TRIP_PERPAY_FAILED);
        }
        return response;
    }

    /**
     * 用户支付行程
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @paramtripNo 行程编号
     * @parampayId支付方式ID 支付宝 微信 余额  银联支付
     * @paramip 微信支付时 客户端终端IP,其他支付时为空
     * @parampayPwd 支付密码 余额支付时必须，其他支付时为空
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject userPayTrip(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "userPayTrip");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo", "payId", "ip", "payPwd")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        Integer payId = ConvertUtil.parseInt(parms.get("payId"));
        String ip = ConvertUtil.parseString(parms.get("ip"));
        String payPwd = ConvertUtil.parseString(parms.get("payPwd"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }

        ip = "127.0.0.1";
        //必须是支付宝,微信支付和余额支付
        if (payId != PayType.Alipay.getId() &&
                payId != PayType.Tenpay.getId() &&
                payId != PayType.UnionPay.getId() &&
                payId != PayType.Balance.getId()) {
            return ResponseResult.exception(response, ErrorCode.PAYMENT_NOT_EXIST);
        }
        //如果是微信支付，需要判断openId,ip不能为空
        if (payId == PayType.Tenpay.getId()) {
            if (StringUtils.isBlank(ip)) {
                return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
            }
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        //判断用户是否存在
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }

        //自己的专线拼车行程
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        query.setOpenId(openId);
        //获取行程
        ServiceTrip trip = serviceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //已经支付
        if (trip.getStatus() != TripStatus.WaitingPay.getValue()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_DEPOSIT_PAYED);
        }
        //行程接单后才能支付剩余部分费用
        /*if (trip.getStatus() < TripStatus.Accept.getValue()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_ACCEPT_CAN_PAY);
        }*/
        //判断行程状态和支付状态
        if (trip.getPayStatus() != null &&
                (trip.getPayStatus() == TradePayStatus.TRADE_SUCCESS.getValue() ||
                        trip.getPayStatus() == TradePayStatus.TRADE_FINISHED.getValue())) {
            return ResponseResult.exception(response, ErrorCode.TRIP_PAYED);
        }

        //double payFee = 0.01;
        double payFee = trip.getPayFee();
        //支付金额小于等于0
        if (payFee <= 0) {
            return ResponseResult.exception(response, ErrorCode.TRIP_PAYFEE_LESS_ZERO);
        }
        if (payId == PayType.Balance.getId()) {
            //判断支付密码
            if (StringUtils.isBlank(payPwd)) {
                return ResponseResult.exception(response, ErrorCode.USER_PAY_PWD_EMPTY);
            }
            String ecPayPwd = encodePayPwd(payPwd);
            //支付密码是否正确
            if (!ecPayPwd.equals(user.getPayPwd())) {
                return ResponseResult.exception(response, ErrorCode.USER_PAY_PWD_ERROR);
            }
            //如果是余额支付判断用户余额是否大于行程支付费用
            double balance = user.getBalance() == null ? 0 : user.getBalance();
            //余额不能小于0，支付费用不能大于余额，表示用户余额不足
            if (balance <= 0 || payFee > balance) {
                return ResponseResult.exception(response, ErrorCode.USER_BALANCE_NOT_ENOUGH);
            }
        }
        Boolean success = false;
        try {
            //支付方式
            String payName = PayType.getPayName(payId);
            //
            //修改行程支付相关的
            ServiceTrip entity = new ServiceTrip();
            entity.setTripNo(tripNo);
            entity.setPayId(payId);
            entity.setPayName(payName);
            entity.setPayStatus(TradePayStatus.WAIT_BUYER_PAY.getValue());
            int row = serviceTripService.updateByKey("", entity);
            success = row > 0;
            //余额支付直接调支付方法，不像支付宝和微信要等待回调再调用支付方法
            if (payId == PayType.Balance.getId()) {
                success = serviceTripService.payTrip("", tripNo, null, null, null, null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        //成功返回支付相关信息
        if (success) {
            try {
                //重新获取一次
                trip = serviceTripService.selectOne("", query);
                Map<String, Object> result = null;
                if (payId == PayType.Balance.getId()) {
                    result = BeanUtil.toMapByFastjson(trip);
                } else {
                    result = setTripPayFeeCallback(trip, payId, ip);
                }
                ResponseResult.success(response, result);
            } catch (Exception e) {
                logger.error(e.getMessage());
                ResponseResult.exception(response, ErrorCode.TRIP_SET_FEE_CALLBACK_FAILED);
            }
        } else {
            ResponseResult.exception(response, ErrorCode.TRIP_PERPAY_FAILED);
        }
        return response;
    }

    /**
     * 用户评价行程
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @paramtripNo 行程编号
     * @paramstar 星级
     * @paramcontent 评价内容
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject userComment(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "userComment");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo", "star", "content")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        Integer star = ConvertUtil.parseInt(parms.get("star"));
        String content = ConvertUtil.parseString(parms.get("content"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        // 必须是自己的行程
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        query.setOpenId(openId);

        ServiceTrip trip = serviceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        // 能评价的行程状态值(完成)
        if (trip.getStatus() != TripStatus.Complete.getValue()) {
            return ResponseResult.exception(response, ErrorCode.STATUS_ERROR);
        }
        //已经评价
        if (trip.getHasComment() != null && trip.getHasComment()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_HAS_COMMENTED);
        }
        Boolean success = false;
        try {
            success = serviceTripService.userComment("", trip, star, content);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            response = ResponseResult.success(response, "评价成功");
        } else {
            response = ResponseResult.exception(response, ErrorCode.TRIP_COMMENT_FAILED);
        }

        return response;
    }

    /**
     * 司机评价行程
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramtripNo 行程编号
     * @paramstar 星级
     * @paramcontent 评价内容
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject driverComment(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverComment");
        //参数检验
        if (!checkRequireParms(parms, "openId", "userOpenId", "tripNo", "star", "content")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String userOpenId = ConvertUtil.parseString(parms.get("userOpenId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        Integer star = ConvertUtil.parseInt(parms.get("star"));
        String content = ConvertUtil.parseString(parms.get("content"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(userOpenId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
		/*User user = userService.getUserByOpenId("", openId);
		if (user == null) {
			return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
		}*/
        // 必须是自己的行程,该行程未包含用户信息，
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        //query.setOpenId(openId);
        query.setDriverOpenId(openId);

        ServiceTrip trip = serviceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        // 能评价的行程状态值(完成)
        if (trip.getStatus() != TripStatus.Complete.getValue()) {
            return ResponseResult.exception(response, ErrorCode.STATUS_ERROR);
        }
        //已经评价
		/*if(trip.getHasComment() != null && trip.getHasComment()){
			return ResponseResult.exception(response, ErrorCode.TRIP_HAS_COMMENTED);
		}*/
        CommentTouser comment1 = new CommentTouser();
        comment1.setToOpenId(userOpenId);//针对用户
        comment1.setToOrderNo(trip.getTripNo());
        CommentTouser comment = commentTouserService.selectOne("", comment1);
        if (comment != null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_HAS_COMMENTED);
        }
        Boolean success = false;
        try {
            success = serviceTripService.driverComment("", trip, userOpenId, star, content);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            response = ResponseResult.success(response, "评价成功");
        } else {
            response = ResponseResult.exception(response, ErrorCode.TRIP_COMMENT_FAILED);
        }

        return response;
    }

    /**
     * 用户投诉行程
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @paramtripNo 行程单号
     * @paramcontent 投诉内容
     * @paramfileList 投诉图片
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject userComplaint(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "userComplaint");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo", "content")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        String content = ConvertUtil.parseString(parms.get("content"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        //投诉内容不能为空
        if (StringUtils.isBlank(content)) {
            return ResponseResult.exception(response, ErrorCode.COMPLAINT_CONTENT_EMPTY);
        }
        User user = userService.getUserByOpenId("", openId);
        if (user == null) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        // 必须是自己的行程
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        query.setOpenId(openId);

        ServiceTrip trip = serviceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        if (trip.getHasComplaint() != null && trip.getHasComment()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_HAS_COMPLAINT);
        }
        List<FileItem> fileList = null;
        if (parms.get("fileList") != null) {
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> list = (List<FileItem>) parms.get("fileList");
                fileList = list;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        Boolean success = false;
        try {
            Complaint complaint = new Complaint();
            complaint.setComplaintNo(SystemUtil.generateOrderNo(""));
            complaint.setComplainant(openId);
            complaint.setOrderNo(tripNo);
            complaint.setContent(content);
            complaint.setStatus(1);//投诉
            complaint.setTime(SystemUtil.getAllSeconds());

            List<ComplaintImages> images = new ArrayList<ComplaintImages>();
            if (fileList != null && !fileList.isEmpty()) {
                for (FileItem fileItem : fileList) {
                    if (StringUtils.isBlank(fileItem.getFileFullUrl()))
                        continue;
                    ComplaintImages image = new ComplaintImages();
                    image.setComplaintNo(complaint.getComplaintNo());
                    image.setImage(fileItem.getFileFullUrl());
                    image.setEnabled(true);
                    images.add(image);
                }
            }
            success = complaintService.userComplaint("", trip, complaint, images);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            response = ResponseResult.success(response, "投诉成功，等待处理");
        } else {
            response = ResponseResult.exception(response, ErrorCode.TRIP_COMPLAINT_FAILED);
        }
        return response;
    }

    /**
     * 司机行程编码，获取乘客行程编码
     *
     * @return
     * @paramparms
     * @paramopenId 司机openId
     * @paramtripNo 司机行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject getTripNoByDriver(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "getTripNoByDriver");
        //参数检验
        if (!checkRequireParms(parms, "openId", "driverTripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(driverTripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        //判断司机的行程是否存在
        ServiceTrip tripQuery = new ServiceTrip();
        tripQuery.setTripNo(driverTripNo);
        tripQuery.setDriverOpenId(openId);
        ServiceTrip trip = serviceTripService.selectOne("", tripQuery);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //获取行程所有乘客
        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(driverTripNo);
        crewsQuery.setDriverOpenId(openId);
        List<ServiceTripCrews> crews = serviceTripCrewsService.selectList("", crewsQuery);
        if (crews != null && crews.size() > 0) {
            ServiceTripCrews crews1 = crews.get(0);
            ResponseResult.success(response, crews1.getCrewTripNo());
        } else {
            response = ResponseResult.success(response, "");
        }
        return response;
    }

    /**
     * 司机发车
     *
     * @return
     * @paramparms
     * @paramopenId 司机openId
     * @paramtripNo 司机行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverSureGo(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverSureGo");
        //参数检验
        if (!checkRequireParms(parms, "openId", "driverTripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(driverTripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        //判断司机的行程是否存在
        ServiceTrip tripQuery = new ServiceTrip();
        tripQuery.setTripNo(driverTripNo);
        tripQuery.setDriverOpenId(openId);

        ServiceTrip trip = serviceTripService.selectOne("", tripQuery);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //行程状态必须是接单和等待中
        if (trip.getStatus() != TripStatus.Accept.getValue()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //获取行程所有乘客
        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(driverTripNo);
        crewsQuery.setDriverOpenId(openId);
        List<ServiceTripCrews> crews = serviceTripCrewsService.selectList("", crewsQuery);
        //司机行程暂无乘客数
        if (trip.getCrewCount() < 1 || crews == null || crews.isEmpty()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_CREWS);
        }
        //包车和快车是先发车在确认用户是否上车，所以不用判断乘客是否上车
        /*if (ServiceCode.BC.getCode().equals(serviceCode)
                || ServiceCode.KC.getCode().equals(serviceCode)) {

            //包车是先发车
        } else {
            //非包车业务需要判断乘客是否都上车
            Boolean allOnTheCar = true;
            for (ServiceTripCrews item : crews) {
                //有乘客还未上车，则不能发车
                if (item.getCrewStatus() != TripCrewStatus.OnTheCar.getValue()) {
                    allOnTheCar = false;
                    break;
                }
            }
            //有乘客还未上车，则不能发车
            if (!allOnTheCar) {
                return ResponseResult.exception(response, ErrorCode.TRIP_HAS_CREW_OFF_THE_CAR);
            }
        }*/

        Boolean success = false;
        try {
            success = serviceTripService.driverSureGo("", trip, crews);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            //response = ResponseResult.success(response, "司机发车成功");
            ServiceTrip query = new ServiceTrip();
            query.setTripNo(driverTripNo);
            ServiceTrip result = serviceTripService.selectByKey("", query);
            ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.TRIP_GO_FAILED);
        }
        return response;
    }

    /**
     * 司机到达乘客位置，等待乘客上车
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramdriverTripNo 司机行程编号
     * @paramuserTripNo 用户行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverArriveStartAdd(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverArriveStartAdd");
        //参数检验
        if (!checkRequireParms(parms, "openId", "driverTripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(driverTripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        //判断司机的行程是否存在
        ServiceTrip tripQuery = new ServiceTrip();
        tripQuery.setTripNo(driverTripNo);
        tripQuery.setDriverOpenId(openId);
        ServiceTrip trip = serviceTripService.selectOne("", tripQuery);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //行程状态必须是已发车
        if (trip.getStatus() != TripStatus.Go.getValue()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //获取行程所有乘客
        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(driverTripNo);
        crewsQuery.setDriverOpenId(openId);
        List<ServiceTripCrews> crews = serviceTripCrewsService.selectList("", crewsQuery);
        //司机行程暂无乘客数
        if (trip.getCrewCount() < 1 || crews == null || crews.isEmpty()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_CREWS);
        }
        Boolean success = false;
        try {
            success = serviceTripService.driverArriveStartAdd("", trip, crews);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ServiceTrip query = new ServiceTrip();
            query.setTripNo(driverTripNo);
            ServiceTrip result = serviceTripService.selectByKey("", query);
            ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.TRIP_GO_FAILED);
        }
        return response;
    }

    /**
     * 司机确认乘客上车行程
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramdriverTripNo 司机行程编号
     * @paramuserTripNo 用户行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverSureUserOnCar(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverSureUserOnCar");
        //参数检验
        if (!checkRequireParms(parms, "openId", "driverTripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        String userTripNo = ConvertUtil.parseString(parms.get("userTripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(driverTripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }

        //判断司机行程是否存在
        ServiceTrip driverTripQuery = new ServiceTrip();
        driverTripQuery.setTripNo(driverTripNo);
        ServiceTrip driverTrip = serviceTripService.selectOne("", driverTripQuery);
        if (driverTrip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //行程状态必须是 发车（城际通），等待用户上车（快车、包车）
        if (driverTrip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
            int driverTripStatus = TripStatus.Go.getValue();
            if ((driverTrip.getStatus() & driverTripStatus) != driverTrip.getStatus()) {
                return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
            }
        } else {
            int driverTripStatus = TripStatus.WaitingPerson.getValue();
            if ((driverTrip.getStatus() & driverTripStatus) != driverTrip.getStatus()) {
                return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
            }
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }

        ///判断用户行程是否存在
        ServiceTrip userTrip = null;
        if (!driverTrip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
            ServiceTrip userTripQuery = new ServiceTrip();
            userTripQuery.setTripNo(userTripNo);
            userTrip = serviceTripService.selectOne("", userTripQuery);
            if (userTrip == null) {
                return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
            }
            int userTripStatus = TripStatus.WaitingPerson.getValue();
            //等待用户上车（快车、包车）
            if ((userTrip.getStatus() & userTripStatus) != userTrip.getStatus()) {
                return ResponseResult.exception(response, ErrorCode.STATUS_ERROR);
            }
        }

        //获取行程所有乘客
        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(driverTripNo);
        crewsQuery.setDriverOpenId(openId);
        List<ServiceTripCrews> crews = serviceTripCrewsService.selectList("", crewsQuery);
        //司机行程暂无乘客数
        if (crews == null || crews.isEmpty()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_CREWS);
        }
        //司机行程乘客
        /*ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(driverTripNo);
        crewsQuery.setCrewTripNo(userTripNo);
        crewsQuery.setDriverOpenId(openId);
        ServiceTripCrews tripCrews = serviceTripCrewsService.selectOne("", crewsQuery);
        //用户行程不属于该行程
        if (tripCrews == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_CREW_NOT_EXIST);
        }*/
        Boolean success = false;
        try {
            success = serviceTripService.driverSureUserOnCar("", driverTrip, userTrip, crews);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            //response = ResponseResult.success(response, "确认用户上车成功");
            ServiceTrip query = new ServiceTrip();
            query.setTripNo(driverTripNo);
            ServiceTrip result = serviceTripService.selectByKey("", query);
            ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.ZXKC_USER_ON_THE_CAR_FAILED);
        }

        return response;
    }


    /**
     * 司机确认乘客下车
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramdriverTripNo 司机行程编号
     * @paramuserTripNo 用户行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverSureUserOffCar(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverSureUserOffCar");
        //参数检验
        if (!checkRequireParms(parms, "openId", "driverTripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        String userTripNo = ConvertUtil.parseString(parms.get("userTripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(driverTripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }

        //判断司机行程是否存在
        ServiceTrip driverTripQuery = new ServiceTrip();
        driverTripQuery.setTripNo(driverTripNo);
        ServiceTrip driverTrip = serviceTripService.selectOne("", driverTripQuery);
        if (driverTrip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //行程状态必须是 发车（城际通），等待用户上车（快车、包车）
        int driverTripStatus = TripStatus.OnTheCar.getValue();
        if ((driverTrip.getStatus() & driverTripStatus) != driverTrip.getStatus()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        ///判断用户行程是否存在
        ServiceTrip userTrip = null;
        if (!driverTrip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
            ServiceTrip userTripQuery = new ServiceTrip();
            userTripQuery.setTripNo(userTripNo);
            userTrip = serviceTripService.selectOne("", userTripQuery);
            if (userTrip == null) {
                return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
            }
            int userTripStatus = TripStatus.OnTheCar.getValue();
            //等待用户上车（快车、包车）
            if ((userTrip.getStatus() & userTripStatus) != userTrip.getStatus()) {
                return ResponseResult.exception(response, ErrorCode.STATUS_ERROR);
            }
        }

        //获取行程所有乘客
        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(driverTripNo);
        crewsQuery.setDriverOpenId(openId);
        List<ServiceTripCrews> crews = serviceTripCrewsService.selectList("", crewsQuery);
        //司机行程暂无乘客数
        if (crews == null || crews.isEmpty()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_CREWS);
        }
        Boolean success = false;
        try {
            success = serviceTripService.driverSureUserOffCar("", driverTrip, userTrip, crews);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ServiceTrip query = new ServiceTrip();
            query.setTripNo(driverTripNo);
            ServiceTrip result = serviceTripService.selectByKey("", query);
            ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.ZXKC_USER_ON_THE_CAR_FAILED);
        }
        return response;
    }


    /**
     * 司机发起支付
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramdriverTripNo 司机行程编号
     * @paramuserTripNo 用户行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverSurePay(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverSurePay");
        //参数检验
        if (!checkRequireParms(parms, "openId", "driverTripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        String userTripNo = ConvertUtil.parseString(parms.get("userTripNo"));
        Double roadPrice = ConvertUtil.parseDouble(parms.get("roadPrice"), 0.00);
        Double parkPrice = ConvertUtil.parseDouble(parms.get("parkPrice"), 0.00);
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(driverTripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }

        //判断司机行程是否存在
        ServiceTrip driverTripQuery = new ServiceTrip();
        driverTripQuery.setTripNo(driverTripNo);
        ServiceTrip driverTrip = serviceTripService.selectOne("", driverTripQuery);
        if (driverTrip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        //行程状态必须是 发车（城际通），等待用户下车（快车、包车）
        int driverTripStatus = TripStatus.OFFTheCar.getValue();
        if ((driverTrip.getStatus() & driverTripStatus) != driverTrip.getStatus()) {
            return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }

        ServiceTrip userTrip = null;
        if (!driverTrip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
            ServiceTrip userTripQuery = new ServiceTrip();
            userTripQuery.setTripNo(userTripNo);
            userTrip = serviceTripService.selectOne("", userTripQuery);
            if (userTrip == null) {
                return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
            }
            int userTripStatus = TripStatus.OFFTheCar.getValue();
            //等待用户上车（快车、包车）
            if ((userTrip.getStatus() & userTripStatus) != userTrip.getStatus()) {
                return ResponseResult.exception(response, ErrorCode.STATUS_ERROR);
            }
        }

        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(driverTripNo);
        crewsQuery.setDriverOpenId(openId);
        List<ServiceTripCrews> crewsList = serviceTripCrewsService.selectList("", crewsQuery);

        Boolean success = false;
        try {
            success = serviceTripService.driverSurePay("", driverTrip, userTrip, crewsList, roadPrice, parkPrice);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            //response = ResponseResult.success(response, "司机发起成功");
            ServiceTrip query = new ServiceTrip();
            query.setTripNo(driverTripNo);
            ServiceTrip result = serviceTripService.selectByKey("", query);
            ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.ZXKC_USER_ON_THE_CAR_FAILED);
        }

        return response;
    }

    /**
     * 司机完成行程
     *
     * @param parms
     * @return
     * @paramopenId 司机openId
     * @paramtripNo 司机行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverCompleteTrip(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "driverCompleteTrip");
        //参数检验
        if (!checkRequireParms(parms, "openId", "driverTripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String driverTripNo = ConvertUtil.parseString(parms.get("driverTripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(driverTripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }

        //判断司机行程是否存在
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(driverTripNo);
        query.setDriverOpenId(openId);

        ServiceTrip driverTrip = serviceTripService.selectOne("", query);
        if (driverTrip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        if (driverTrip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
            //行程状态必须是行程中(城际通)
            if (driverTrip.getStatus() != TripStatus.OFFTheCar.getValue()) {
                return ResponseResult.exception(response, ErrorCode.TRIP_STATUS_ERROR);
            }
        } else {
            //专车、快车必须支付
            if (driverTrip.getStatus() != TripStatus.Payed.getValue() || driverTrip.getPayStatus() != TradePayStatus.TRADE_SUCCESS.getValue()) {
                return ResponseResult.exception(response, ErrorCode.TRIP_HAS_CREW_NOT_PAYED);
            }
        }
        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(driverTripNo);
        crewsQuery.setDriverOpenId(openId);
        List<ServiceTripCrews> crewsList = serviceTripCrewsService.selectList("", crewsQuery);
        //是否所以乘客都支付
        Boolean isALlPay = true;
        if (crewsList != null && !crewsList.isEmpty()) {
            for (ServiceTripCrews item : crewsList) {
                if (!item.getPayStatus()) {
                    isALlPay = false;
                    break;
                }
            }
        }
        if (!isALlPay) {
            return ResponseResult.exception(response, ErrorCode.TRIP_HAS_CREW_NOT_PAYED);
        }

        Boolean success = false;
        try {
            success = serviceTripService.driverCompleteTrip("", driverTrip);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            query = new ServiceTrip();
            query.setTripNo(driverTripNo);
            ServiceTrip result = serviceTripService.selectByKey("", query);
            ResponseResult.success(response, result);
        } else {
            ResponseResult.exception(response, ErrorCode.TRIP_COMPLETE_FAILED);
        }
        return response;
    }

    /**
     * 用户获取行程列表
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @paraserviceCode服务业务代码
     * @paramstatus 行程状态
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject userGetTripList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "userGetTripList");
        //参数检验
        if (!checkRequireParms(parms, "openId", "serviceCode", "status", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!userService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        }
        //业务代码为空表示所有业务
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        int status = ConvertUtil.parseInt(parms.get("status"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;
        Sort sort = new Sort(Direction.DESC, "create_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);
        ServiceTrip query = new ServiceTrip();
        query.setStatus(status);
        query.setServiceCode(serviceCode);
        query.setUserType(PlatformUserType.CLIENT_USER.getValue());
        query.setOpenId(openId);

        List<ServiceTrip> result = serviceTripService.selectList("", query, pageable);
        response = ResponseResult.success(response, result);

        return response;
    }


    /**
     * 获取行程信息
     *
     * @param parms
     * @return
     * @paramopenId openId
     * @paramtripNo 行程编号
     */
    @ApiVersion(value = {1})
    public ResponseObject getTripInfo(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "getTripInfo");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);

        ServiceTrip result = serviceTripService.selectOne("", query);
        if (result == null) {
            response = ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        } else {
            response = ResponseResult.success(response, result);
        }
        return response;
    }


    /**
     * 获取行程用户信息
     *
     * @param parms
     * @return
     * @paramopenId openId
     * @paramtripNo 行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject getTripUser(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "getTripUser");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        query.setServiceCode(ServiceCode.BC.getCode());
        query.setUserType(PlatformUserType.CLIENT_USER.getValue());

        ServiceTrip trip = serviceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        String userOpenId = trip.getOpenId();
        LinkUser result = userService.getLinkUser("", userOpenId);
        if (result == null) {
            response = ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
        } else {
            response = ResponseResult.success(response, result);
        }
        return response;
    }

    /**
     * 获取行程司机信息
     *
     * @param parms
     * @return
     * @paramopenId openId
     * @paramtripNo 行程编号
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject getTripDriver(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "getTripDriver");
        //参数检验
        if (!checkRequireParms(parms, "openId", "tripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }
        ServiceTrip query = new ServiceTrip();
        query.setTripNo(tripNo);
        query.setServiceCode(ServiceCode.BC.getCode());
        query.setUserType(PlatformUserType.CLIENT_USER.getValue());

        ServiceTrip trip = serviceTripService.selectOne("", query);
        if (trip == null) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NOT_EXIST);
        }
        String driverOpenId = trip.getDriverOpenId();
        LinkDriver result = driverService.getLinkDriver("", driverOpenId);
        if (result == null) {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        } else {
            response = ResponseResult.success(response, result);
        }
        return response;
    }


    /**
     * 获取费用明细
     *
     * @param parms
     * @return
     * @paramopenId 用户openId
     * @paraserviceCode服务业务代码
     * @paramstatus 行程状态
     * @parampageIndex 分页索引
     * @parampageSize 分页每页条数
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.client)
    public ResponseObject getTripPriceRecord(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("trip", "getTripPriceRecord");
        //参数检验
        if (!checkRequireParms(parms, "tripNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String tripNo = ConvertUtil.parseString(parms.get("tripNo"));
        if (StringUtils.isBlank(tripNo)) {
            return ResponseResult.exception(response, ErrorCode.TRIP_NO_EMPTY);
        }

        Sort sort = new Sort(Direction.ASC, "update_time");
        ServicePriceRecord query = new ServicePriceRecord();
        query.setTripNo(tripNo);

        List<ServicePriceRecord> result = servicePriceRecordService.selectList("", query, sort);
        response = ResponseResult.success(response, result);

        return response;
    }
}
